<?php


namespace app\index\model;


use think\facade\Cache;
use think\Model;

class SensitiveWord extends Model
{
    protected $name = 'admin_sensitive_word';

    /**
     * 获取敏感词
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getBadWord()
    {
        $cacheSensitiveWord = Cache::get('sensitiveWord');
        if (!$cacheSensitiveWord) {

            $sensitiveWord = SensitiveWord::select();

            $cacheSensitiveWord = '';
            foreach ($sensitiveWord as $v) {
                $cacheSensitiveWord .= trim($v['badword']).'|';
            }
            Cache::set('sensitiveWord',$cacheSensitiveWord);
        }
        return $cacheSensitiveWord;
    }

    /**
     * 检测是否存在敏感词
     * @param $param
     * @param $baddata
     * @return bool
     */
    public static function checkBadWord($param,$baddata)
    {
        // 转换成数组并过滤空数据
        $arr = array_filter(explode("|", rtrim($baddata,'|')));
        $count = count($arr);
        for ($i = 0; $i < $count; $i++) {
            // 如果此数组元素为空则跳过此次循环
            if (empty($arr[$i])) {
                continue;
            }
            // 查找字符串第一次出现的位置，如果检测到关键字，则返回匹配的关键字，并终止运行
//            var_dump($arr[$i],$param,stripos($param,trim($arr[$i])));
            if (strpos($param,trim($arr[$i])) != false) {
                return $arr[$i];
            }
        }
        // 如果没有检测到关键字则返回false
        return false;
    }
}